import { readFileSync, writeFileSync } from "fs";

function addNote(title, body) {
  console.log("Adding New Note");
  let outNote = {
    title: title,
    body: content
  };

  let notes = JSON.parse(readFileSync("notes.json"));

  // console.log(JSON.stringify(notes));
  notes.push(outNote);

  writeFileSync("notes.json", JSON.stringify(notes), (err) => {
      if(err) throw err;
  });
  return outNote;
}

function searchNoteByTitle(title) {
  console.log(`Searching Notes For Title ${title}`);
  let notes = JSON.parse(readFileSync("notes.json"));
  let count = 0;
  let return_notes = [];
  for(const obj of notes)
    if(obj.title === title){
      return_notes.push(obj);
      count++;
    }
  return { count: count, notes: return_notes };
}

function listNotes() {
  console.log("Listing all notes");
  let count = 0;
  let notes = JSON.parse(readFileSync("notes.json"));
  for(const obj of notes){
    console.log(`title: ${obj.title}\ncontent: ${obj.content}`);
    count++;
  }
  return { count: count, notes: notes };
}

function removeNotesByTitle(title) {
  console.log("Removing note");
  let notes = JSON.parse(readFileSync("notes.json"));
  notes = notes.filter(item => item.title !== title);
  writeFileSync("notes.json", JSON.stringify(notes), (err) => {
    if(err) throw err;
  });
  return { message: `标题为 ${title} 的笔记已被删除!` };
}

function modifyNotesByTitle(title, content) {
  console.log("Modifying note");
  let notes = JSON.parse(readFileSync("notes.json"));
  let el = notes.find(item => item.title === title);
  let i = notes.indexOf(el);
  el.content = content;
  notes[i] = el;
  writeFileSync("notes.json", JSON.stringify(notes), (err) => {
    if(err) throw err;
  });
  return { message: `标题为 ${title} 的笔记已被修改!` };
}

export { addNote, searchNoteByTitle, listNotes, removeNotesByTitle, modifyNotesByTitle }